package br.com.ambgis.sicap;

import static br.com.ambgis.sicap.Constants.DEBUG;
import static br.com.ambgis.sicap.Constants.TAG;

import java.io.File;
import java.io.IOException;
import java.util.Locale;

import android.location.Location;
import android.media.ExifInterface;
import android.util.Log;

public class ExifEditor {

	private ExifInterface exif = null;
	private File imgFile = null;

	public ExifEditor(File imgFile) {
		this.imgFile = imgFile;
		try {
			this.exif = new ExifInterface(imgFile.getAbsolutePath());
		} catch (IOException e) {
			throw new RuntimeException("Can't read Exif attributes from file " + imgFile, e);		
		}
	}

	public String readAttribute(String tag) {
		return exif.getAttribute(tag);
	}
	
	public void setGpsInfo(Location loc) {
		if (loc == null) return;
		
        double lat = loc.getLatitude();
        double lon = loc.getLongitude();

		String latRef = lat < 0 ? "S" : "N";
		exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE_REF, latRef);
		
		lat = Math.abs(lat);
		double[] dms = convertDecimalToDms(lat);
		String latValue = String.format(Locale.US, "%d/1,%d/1,%f/1", (long) dms[0], (long) dms[1], dms[2]);
		if (DEBUG) Log.d(TAG, "Setting GPS Latitude: " + latValue);
		exif.setAttribute(ExifInterface.TAG_GPS_LATITUDE, latValue);
		
		String lonRef = lon < 0 ? "W" : "E";
		exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF, lonRef);
		
		lon = Math.abs(lon);
		dms = convertDecimalToDms(lon);
		String lonValue = String.format(Locale.US, "%d/1,%d/1,%f/1", (long) dms[0], (long) dms[1], dms[2]);
		if (DEBUG) Log.d(TAG, "Setting GPS Longitude: " + latValue);
		exif.setAttribute(ExifInterface.TAG_GPS_LONGITUDE, lonValue);
		
		try {
			exif.saveAttributes();
		} catch (IOException e) {
			throw new RuntimeException("Can't write GPS info into JPEG file " + imgFile.getAbsolutePath(), e);
		}
	}

	private double[] convertDecimalToDms(double coordinate) {
		double value = coordinate;
		double degrees = (long) value;
		value %= 1;
		value *= 60.0;
		double minutes = (long) value;
		value %= 1;
		value *= 60.0;
		double seconds = value;
		return new double[] { degrees, minutes, seconds };
	}
	
	public Boolean hasGpsInfo() {
		return exif.getAttribute(ExifInterface.TAG_GPS_LATITUDE) != null
				&& exif.getAttribute(ExifInterface.TAG_GPS_LONGITUDE) != null;
	}

}